use base64::prelude::*;

fn xor_encrypt_decrypt(data: &[u8], key: u8) -> Vec<u8> {
    data.iter().map(|&b| b ^ key).collect() // 对每个字节进行 XOR 操作
}
// Java代码参考 XORCipher.java
fn main() {
    let text = "Hello, 世界!127.0.0.1 56"; // 包含中文
    let key = 'x'; // 选择一个字符作为密钥
    let encoded_encrypted = encode(key, text);
    println!("Original: {}", text);
    println!("Encrypted (Base64): {}", encoded_encrypted);
    let encoded_encrypted ="MB0UFBdUWJzA7p/t9FlJSk9WSFZIVklYTU5YWBAMDAhCV1cUFxsZFBAXCwxCSUpLTFcZVhUITFg9Qlc6GREcDTYdDBwRCxM8Fw8WFBcZHFdISVaR0+Ce7cid58Kf2fhXSEme7sie7v+R+euf8fCe5NRXS0lWn9TUnMLsn9PYVZ3W4p/f153w/p/i/J3C7J/s0FYVCEw=x";
    let decrypted = decode(&encoded_encrypted);
    /*
       // 将原始文本转换为字节数组
       let original_bytes = text.as_bytes();

       // 加密
       let encrypted_bytes = xor_encrypt_decrypt(original_bytes, key);
       // 对加密结果进行 Base64 编码
       let encoded_encrypted = BASE64_STANDARD.encode(&encrypted_bytes);

       // 解密（首先进行 Base64 解码）
       let decoded_encrypted = BASE64_STANDARD
           .decode(&encoded_encrypted)
           .expect("Failed to decode base64");
       let decrypted_bytes = xor_encrypt_decrypt(&decoded_encrypted, key);
       // 将解密后的字节数组转换回字符串
       let decrypted = String::from_utf8(decrypted_bytes).expect("Failed to convert bytes to String");
    */

    println!("Decrypted: {}", decrypted);
}

fn encode(key: char, text: &str) -> String {
    let key_bytes = 'x' as u8; // 选择一个字符作为密钥
                               // 将原始文本转换为字节数组
    let original_bytes = text.as_bytes();
    // 加密
    let encrypted_bytes = xor_encrypt_decrypt(original_bytes, key_bytes);
    // 对加密结果进行 Base64 编码
    let mut encoded_encrypted = BASE64_STANDARD.encode(&encrypted_bytes);
    // 把key 放到最后
    encoded_encrypted.push(key);
    encoded_encrypted
}

fn decode(text: &str) -> String {
    // 分割字符串
    let (encoded_encrypted, key_str) = text.split_at(text.len() - 1);
    // 获取key
    let key = key_str.chars().next().unwrap() as u8;
    // 解密（首先进行 Base64 解码）
    let decoded_encrypted = BASE64_STANDARD
        .decode(&encoded_encrypted)
        .expect("Failed to decode base64");
    let decrypted_bytes = xor_encrypt_decrypt(&decoded_encrypted, key);
    // 将解密后的字节数组转换回字符串
    let decrypted = String::from_utf8(decrypted_bytes).expect("Failed to convert bytes to String");
    decrypted
}
